/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */

$(function(){
    
	//open the deletion dialog when the delete entry link clicked
	$("#ve_action_delete").on('click',function(){	
		var form_id  = $("#ve_details").data("formid");
		var entry_id = $("#ve_details").data("entryid"); 
		var selected_entry = [{name: "entry_" + entry_id, value: "1"}];
		var csrf_token  = $("#ve_details").data("csrftoken");

		Swal.fire({
				title: 'Are you sure you want to delete this entry?',
				html: 'Data and files associated with this entry will be deleted.',
				footer: 'This action cannot be undone.',
				icon: 'warning',
				width: '40%',
				customClass: {
					htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom',
					footer: 'swal2-footer-warning',
					title: 'swal2-title-warning'
				},
				showCancelButton: true,
				confirmButtonText: 'Yes. Delete this entry',
				showLoaderOnConfirm: true,
				preConfirm: () => {
					return axios.post('delete_entries.php', {
						form_id: form_id,
						csrf_token: csrf_token,
						origin: 'view_entry',
						incomplete_entries: $("#ve_details").data("incomplete"),
						selected_entries: selected_entry
					})
					.then(function (response) {
						if(response.data.status == 'ok'){
							//redirect to entries page again
							if(response.data.entry_id != '0' && response.data.entry_id != ''){
								window.location.replace('view_entry.php?form_id=' + response.data.form_id + '&entry_id=' + response.data.entry_id);
							}else{
								window.location.replace('manage_entries.php?id=' + response.data.form_id);
							}

							return response;
						}else{
							Swal.showValidationMessage('Error: Unable to process. Please try again later.');
						}
					})
					.catch(function (error) {
						Swal.showValidationMessage("Error: " + error);
					})
				},
				allowOutsideClick: () => !Swal.isLoading()
		});

		return false;
	});

	//open the change status dialog when the status link clicked
	$("#ve_action_status").on('click',function(){
		var form_id  = $("#ve_details").data("formid");
		var entry_id = $("#ve_details").data("entryid"); 
		var csrf_token  = $("#ve_details").data("csrftoken");

		Swal.fire({
				title: 'Change entry status to incomplete?',
				html: 'This entry will be marked as incomplete. <br/>Your client will be able to resume/edit the entry again.',
				icon: 'warning',
				width: '40%',
				customClass: {
					htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom',
					title: 'swal2-title-warning'
				},
				showCancelButton: true,
				confirmButtonText: 'Yes. Mark as incomplete',
				showLoaderOnConfirm: true,
				didOpen: () => {
					var clipboard = new ClipboardJS('.trigger-edit-resume-link-alert');
					clipboard.on('success', function(e) {
						//display notifications on success
						Swal.fire({
							toast: true,
							position: 'center',
							icon: 'success',
							title: 'Link copied.',
							showConfirmButton: false,
							timer: 2000,
							didDestroy: () => {
								window.location.replace('view_entry.php?form_id=' + form_id + '&entry_id=' + entry_id);
							}
						});
					});
				},
				preConfirm: () => {
					return axios.post('change_entry_status.php', {
						form_id: form_id,
						csrf_token: csrf_token,
						entry_id: entry_id
					})
					.then(function (response) {
						if(response.data.status == 'ok'){
							//display success and the resume link
							Swal.fire({
								icon: 'success',
								title: 'Entry marked incomplete.',
								html: 'You can send the following <strong>Resume URL</strong> to your client:' + 
									  '<div id="div_dialog_encryption_success" style="padding: 15px;margin-top:10px">' +
									  '<input onclick="javascript: this.select()" type="text" value="' + response.data.resume_url + '" class="text" name="form-resume-link-alert" id="form-resume-link-alert" />' +
									  '</div>' + 
									  '<a class="blue_dotted trigger-edit-resume-link-alert" href="javascript:void(0)" id="form_resume_url_link_alert" data-clipboard-action="copy" data-clipboard-target="#form-resume-link-alert" style="font-weight:bold">Copy Link</a>',
								width: '40%',
								customClass: {
									title: 'swal2-title-success',
									htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom'
								},
								didClose: () => {
									window.location.replace('view_entry.php?form_id=' + form_id + '&entry_id=' + entry_id);
								},
								confirmButtonText: 'Done',
								showCancelButton: false,
								showConfirmButton: true,
								allowOutsideClick: true
							});

							return response;
						}else{
							Swal.showValidationMessage('Error: Unable to process. Please try again later.');
						}
					})
					.catch(function (error) {
						Swal.showValidationMessage("Error: " + error);
					})
				},
				allowOutsideClick: () => !Swal.isLoading()
		});

		return false;
	});

	//dialog box to decrypt the entry
	$("#button_decrypt_entry_data").on('click',function(){
		Swal.fire({
			title: 'Enter Your Private Key',
			width: '30%',
			input: 'text',
			footer: 'Correct Private Key is needed to view encrypted data.',
			customClass: {
				htmlContainer: 'swal2-html-container-bold',
				title: 'swal2-title-warning',
				input: 'swal2-text-center'
			},
			showCancelButton: true,
			confirmButtonText: 'Submit',
			showLoaderOnConfirm: true,
			preConfirm: (private_key) => {
				if(private_key == ''){
					Swal.showValidationMessage('Error: Please enter your private key!');
					return false;
				}
				
				var form_id  = $("#ve_details").data("formid");
				var entry_id = $("#ve_details").data("entryid"); 
				var csrf_token = $("#ve_details").data("csrftoken");

				return axios.post('encryption_set_privatekey.php', {
					form_id: form_id,
					csrf_token: csrf_token,
					private_key: private_key
				})
				.then(function (response) {
					if(response.data.status == 'ok'){
						 //reload the page
						 window.location.replace('view_entry.php?form_id=' + form_id + '&entry_id=' + entry_id);
					}else{
						Swal.showValidationMessage('Error: Unable to process. Please try again later.');
					}
				})
				.catch(function (error) {
					Swal.showValidationMessage("Error: " + error);
				});
			},
			allowOutsideClick: () => !Swal.isLoading()
		});

		return false;
	});

	//if the user submit the form by hitting the enter key, make sure to call the button-decrypt-entry handler
	$("#dialog-decrypt-entry-form").on("submit",function(){
		$("#dialog-decrypt-entry-btn-ok").trigger("click");
		return false;
	});

	//open the email entry dialog when the email entry link clicked
	$("#ve_action_email").on('click',function(){	
		var form_id  = $("#ve_details").data("formid");
		var entry_id = $("#ve_details").data("entryid"); 
		var csrf_token  = $("#ve_details").data("csrftoken");

		Swal.fire({
			title: 'Email Entry #' + entry_id,
			html: $("#dialog-email-entry").html(),
			width: '26%',
			customClass: {
				title: 'swal2-title-warning',
				htmlContainer: 'swal2-html-container-left swal2-html-container-email-entry'
			},
			didOpen: () => {
				init_email_entry_handlers();
				$("#dialog-email-entry-input").trigger("focus");
			},
			confirmButtonText: '<span class="icon-paper-plane"></span> Email Entry',
			cancelButtonText: 'Cancel',
			showCancelButton: true,
			showConfirmButton: true,
			showLoaderOnConfirm: true,
			allowOutsideClick: () => !Swal.isLoading(),
			preConfirm: () => {
		
				if($("#dialog-email-entry-input").val() == ""){
					Swal.showValidationMessage('Error: Please enter the email address!');
					return false;
				}

				return axios.post('email_entry.php', {
					form_id: form_id,
					entry_id: entry_id,
					csrf_token: csrf_token,
					email_template: $("#dialog-email-entry-template").val(),
					target_email: $("#dialog-email-entry-input").val(),
					email_note: $("#dialog-email-entry-note").val()
				})
				.then(function (response) {
					if(response.data.status == 'ok'){
						Swal.fire({
							toast: true,
							position: 'center',
							icon: 'success',
							title: 'The entry has been sent.',
							showConfirmButton: false,
							timer: 2000
						});
						
						return response;
					}else{
						Swal.showValidationMessage('Error: Unable to process. Please try again later.');
					}
				})
				.catch(function (error) {
					Swal.showValidationMessage("Error: " + error);
				});
			}
		});

		return false;
	});

	//attach event to "change payment status" link
	$("#payment_status_change_link").on('click',function(){	
		$("#payment_status_static").hide();
		$("#payment_status_form").show();

		return false;
	});

	//attach event to "cancel" link on payment status
	$("#payment_status_cancel_link").on('click',function(){	
		$("#payment_status_form").hide();
		$("#payment_status_static").show();

		return false;
	});

	//attach event to "save" link on payment status
	$("#payment_status_save_link").on('click',function(){	
		
		$("#payment_status_dropdown").prop("disabled",true);
		$("#payment_status_save_cancel").hide();
		$("#payment_status_loader").show();

		var form_id  = $("#ve_details").data("formid");
		var entry_id = $("#ve_details").data("entryid");
		var csrf_token  = $("#ve_details").data("csrftoken");

		//do the ajax call to change payment status
		axios.post('change_payment_status.php', {
			form_id: form_id,
			entry_id: entry_id,
			csrf_token: csrf_token,
			payment_status: $("#payment_status_dropdown").val()
		})
		.then(function (response) {
			//restore the link and update the payment status
			$("#payment_status_dropdown").prop("disabled",false);
			$("#payment_status_save_cancel").show();
			$("#payment_status_loader").hide();

			if(response.data.status == 'ok'){
				$(".payment_status").removeClass('paid').text(response.data.payment_status.toUpperCase());	

				if(response.data.payment_status == 'paid'){
					$(".payment_status").addClass('paid');
				}

				$("#payment_status_form").hide();
				$("#payment_status_static").show();
			}else{
				Swal.fire({
					width: '30%',
					position: 'center',
					icon: 'error',
					title: 'Error. Unable to complete the task.',
					html: response.data,
					showConfirmButton: false,
					showCancelButton: true,
					cancelButtonText: 'Close',
					allowOutsideClick: true
				});
			}
		})
		.catch(function (error) {
			Swal.fire({
				width: '30%',
				position: 'center',
				icon: 'error',
				title: 'Error. Unable to complete the task.',
				html: error,
				showConfirmButton: false,
				showCancelButton: true,
				cancelButtonText: 'Close',
				allowOutsideClick: true
			});
		});

		return false;
	});

	function init_email_entry_handlers(){
		//Attach event to "more options" 
		$("#more_option_email_entry").on('click',function(){
			if($(this).text() == 'more options'){
				//expand more options
				$("#ve_box_email_more").slideDown();
				$(this).text('hide options');
			}else{
				$("#ve_box_email_more").slideUp();
				$(this).text('more options');
			}

			return false;
		});

		//Attach event "..." recent emails button
		$("#toggle-recent-emails").on('click',function(){

			if($(this).text() == '>'){
				$("#email-entry-suggestion-full").slideDown();
				$(this).text('x');
			}else{
				$("#email-entry-suggestion-full").slideUp();
				$(this).text('>');
			}

			return false;
		});

		$(".email-entry-suggestion-link:not(.email-entry-suggestion-toggle)").on('click',function(){
			if($("#dialog-email-entry-input").val().length > 0){
				$("#dialog-email-entry-input").val($("#dialog-email-entry-input").val() + ',' + $(this).text());
			}else{
				$("#dialog-email-entry-input").val($(this).text());
			}
			
			$(this).remove();

			if($(".email-entry-suggestion-link:not(.email-entry-suggestion-toggle)").length == 0){
				$(".email-entry-suggestion-link,.email-entry-suggestion-toggle,#infomessage_recent_emails").remove();
			}

			if($("#email-entry-suggestion-full .email-entry-suggestion-link").length == 0){
				$(".email-entry-suggestion-toggle").remove();
			}

			return false;
		});

		//if the user submit the form by hitting the enter key, make sure to call the button-email-entry handler
		$("#dialog-email-entry-form").on("submit",function(){
			$(".swal2-confirm").trigger("click");
			return false;
		});
	}

	//Attach event to approval buttons (approve/deny)
	$("#button_approval_approve,#button_approval_deny").on('click',function(){
		var selected_button = $(this).attr("id");
		var approval_state  = '';

		if($(this).text() == 'Processing...'){
			return false;
		}

		var form_id  = $("#ve_details").data("formid");
		var entry_id = $("#ve_details").data("entryid");
		var csrf_token = $("#ve_details").data("csrftoken"); 

		if(selected_button == 'button_approval_approve'){
			approval_state = 'approved';
			
			$("#button_approval_approve").text("Processing...");
			$("#button_approval_deny").hide();
		}else if(selected_button == 'button_approval_deny'){
			approval_state = 'denied';

			$("#button_approval_deny").text("Processing...");
			$("#button_approval_approve").hide();
		}

		//hide the approval buttons while processing
		$("#button_approval_deny").after("<div class='small_loader_box' style=\"float: none; display: inline;padding: 0; margin-left: 5px;\"><img src='images/loader_small_grey.gif' /></div>");

		//do the ajax call to approve the entry
		axios.post('approve_deny_entry.php', {
			form_id: form_id,
			entry_id: entry_id,
			csrf_token: csrf_token,
			approval_state: approval_state,
			approval_note: $("#ve-approval-add-note").val(),
			show_message: '1'
		})
		.then(function (response) {
			if(response.data.status == 'ok'){
				window.location.replace('view_entry.php?form_id=' + response.data.form_id + '&entry_id=' + response.data.entry_id);
			}else{
				Swal.fire({
					width: '30%',
					position: 'center',
					icon: 'error',
					title: 'Error. Unable to complete the task.',
					html: response.data,
					showConfirmButton: false,
					showCancelButton: true,
					cancelButtonText: 'Close',
					allowOutsideClick: true
				});
			}
		})
		.catch(function (error) {
			Swal.fire({
				width: '30%',
				position: 'center',
				icon: 'error',
				title: 'Error. Unable to complete the task.',
				html: error,
				showConfirmButton: false,
				showCancelButton: true,
				cancelButtonText: 'Close',
				allowOutsideClick: true
			});
		});

		return false;
	});

	//copy link to clipboard event handler
	var clipboard = new ClipboardJS('.trigger-edit-resume-link');
    clipboard.on('success', function(e) {
        //display notifications on success
		Swal.fire({
		  toast: true,
		  position: 'center',
		  icon: 'success',
		  title: 'Link copied.',
		  showConfirmButton: false,
		  timer: 2000
		});
    });

	
});